namespace Legend
{
    using System;

    /// <summary>
    /// Converts to and from Guids and short string representations.
    /// </summary>
    public class ShortGuidConverter
        : TypeConverterBase<Guid, string>
    {
        protected override Guid ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, string value)
        {
            string guidString = ToBase64String(value);
            var bytes = Convert.FromBase64String(guidString);
            return new Guid(bytes);
        }

        protected override string ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, Guid value)
        {
            var bytes = value.ToByteArray();
            var base64 = Convert.ToBase64String(bytes);
            return ToUrlSafeString(base64);
        }

        private static string ToUrlSafeString(string base64String)
        {
            string escaped = EscapeGuidString(base64String);
            return escaped.Substring(0, base64String.Length - 2);
        }

        private static string ToBase64String(string value)
        {
            string unEscapedValue = UnEscapeGuidString(value);
            return unEscapedValue + "==";
        }

        private static string EscapeGuidString(string base64String)
        {
            return base64String.Replace("/", "_").Replace("+", "-");
        }

        private static string UnEscapeGuidString(string value)
        {
            return value.Replace("_", "/").Replace("-", "+");
        }
    }
}
